﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using FairyGUI;
using System;
using System.IO;

public class FMapEditorMediator : MyWindow {

    #region Attribute
    //层数列表
    GList _layerList;
    Dictionary<GMConfig.ProductType,GList> _lists;
    Dictionary<GMConfig.CountRange, List<GTextInput>> _countRangeDic;
    List<GComponent> roomGComps;
    List<GGroup> groupList;
    Map _map;
    List<FixedRoom> fixedRoomList;
    List<string> _randomFixedRoomList;
    FileInfo[] blocks;
    #endregion

    static FMapEditorMediator _instance;
    public FMapEditorMediator(){
        this.contentPane = UIPackage.CreateObject("MapPackages", "MapEditor").asCom;
        groupList = new List<GGroup>();
        roomGComps = new List<GComponent>();
        _lists = new Dictionary<GMConfig.ProductType, GList>();
        _countRangeDic = new Dictionary<GMConfig.CountRange, List<GTextInput>>();

        _layerList = this.contentPane.GetChild("LayerList").asList;

        _lists.Add(GMConfig.ProductType.Item, this.contentPane.GetChild("ItemList").asList);
        _lists.Add(GMConfig.ProductType.Event, this.contentPane.GetChild("EventList").asList);
        _lists.Add(GMConfig.ProductType.Card, this.contentPane.GetChild("CardList").asList);
        _lists.Add(GMConfig.ProductType.Boss, this.contentPane.GetChild("BossList").asList);
        _lists.Add(GMConfig.ProductType.BossRetinue, this.contentPane.GetChild("BossRetinueList").asList);
        _lists.Add(GMConfig.ProductType.Elite, this.contentPane.GetChild("EliteList").asList);
        _lists.Add(GMConfig.ProductType.EliteRetinue, this.contentPane.GetChild("EliteRetinueList").asList);
        _lists.Add(GMConfig.ProductType.Monster, this.contentPane.GetChild("MonsterList").asList);
        _lists.Add(GMConfig.ProductType.InsertRoom, this.contentPane.GetChild("InsertRoomList").asList);

        _countRangeDic.Add(GMConfig.CountRange.Room, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("numInput_01").asTextInput,
                        this.contentPane.GetChild("numInput_02").asTextInput
                        }));

        _countRangeDic.Add(GMConfig.CountRange.Item, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("itemInput_01").asTextInput,
                        this.contentPane.GetChild("itemInput_02").asTextInput
                        }));

        _countRangeDic.Add(GMConfig.CountRange.Event, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("eventInput_01").asTextInput,
                        this.contentPane.GetChild("eventInput_02").asTextInput }));

        _countRangeDic.Add(GMConfig.CountRange.BossRetinue, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("bossRetinueInput_01").asTextInput,
                        this.contentPane.GetChild("bossRetinueInput_02").asTextInput }));

        _countRangeDic.Add(GMConfig.CountRange.Elite, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("eliteInput_01").asTextInput,
                        this.contentPane.GetChild("eliteInput_02").asTextInput }));

        _countRangeDic.Add(GMConfig.CountRange.EliteRetinue, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("eliteRetinueInput_01").asTextInput,
                        this.contentPane.GetChild("eliteRetinueInput_02").asTextInput }));

        _countRangeDic.Add(GMConfig.CountRange.Monster, new List<GTextInput>(new GTextInput[2]{
                        this.contentPane.GetChild("monsterInput_01").asTextInput,
                        this.contentPane.GetChild("monsterInput_02").asTextInput }));

        roomGComps.Add(this.contentPane.GetChild("BossRoom").asCom);
        roomGComps.Add(this.contentPane.GetChild("EliteRoom").asCom);
        roomGComps.Add(this.contentPane.GetChild("MonsterRoom").asCom);

        _lists.Add(GMConfig.ProductType.BossRoom, roomGComps[0].GetChild("List").asList);
        _lists.Add(GMConfig.ProductType.EliteRoom, roomGComps[1].GetChild("List").asList);
        _lists.Add(GMConfig.ProductType.MonsterRoom, roomGComps[2].GetChild("List").asList);


        groupList.Add(this.contentPane.GetChild("LayerGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("ItemGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("EventGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("CardGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("BossGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("BossRetinueGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("EliteGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("EliteRetinueGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("MonsterGrou").asGroup);
        groupList.Add(this.contentPane.GetChild("InsertRoomGrou").asGroup);
        
    }
    protected override void OnInit()
    {
        base.OnInit();
        this.Center();//居中

        InitLists();
        AddClickEvent();
    }

    protected override void OnShown(){
        base.OnShown();
    }

    void AddClickEvent(){
        foreach (GGroup group in groupList)
        {
            this.contentPane.GetChildInGroup(group, "AddBtn").asButton.onClick.Add(() =>
            {
                switch (group.name)
                {
                    case "LayerGrou":
                        //添加一层，数据加入一层地图
                        MapManager.Instance.InsertMap(new Map(),_layerList.selectedIndex + 1);
                        _layerList.numItems++;
                        break;
                    //插入房间
                    case "InsertRoomGrou":
                        LoadCommonListPanel(GMConfig.ProductType.InsertRoom);
                        break;
                    case "EventGrou":
                        LoadCommonListPanel(GMConfig.ProductType.Event);
                        break;
                    //杂物
                    case "ItemGrou":
                        FItemListMediator itemListMediator = FUIMain.ShowPanel(GMConfig.PanelType.ItemList) as FItemListMediator;
                        itemListMediator.loadItem = (int index) => {

                            List<Item> _dataList = ItemManager.Instance._itemList;
                            Item data = _dataList[index];

                            MapManager.Instance.AddKeyValue(_map, GMConfig.ProductType.Item, new KeyValue(data.name, 0));
                            GList list = _lists[GMConfig.ProductType.Item];
                            list.numItems++;
                        };
                        break;
                    //卡牌
                    case "CardGrou":
                        LoadCommonListPanel(GMConfig.ProductType.Card);
                        break;
                    //Boss
                    case "BossGrou":
                        LoadCommonListPanel(GMConfig.ProductType.Boss);
                        break;
                    case "BossRetinueGrou":
                        LoadCommonListPanel(GMConfig.ProductType.BossRetinue);
                        break;
                    case "EliteGrou":
                        LoadCommonListPanel(GMConfig.ProductType.Elite);
                        break;
                    case "EliteRetinueGrou":
                        LoadCommonListPanel(GMConfig.ProductType.EliteRetinue);
                        break;
                    case "MonsterGrou":
                        LoadCommonListPanel(GMConfig.ProductType.Monster);
                        break;
                }
            });
            this.contentPane.GetChildInGroup(group, "RemoveBtn").asButton.onClick.Add(() =>
            {
                FUIMain.TipPanel("是否确定删除本条数据？",(status) =>
                {
                    if ((int)status == 1)
                    {
                        GList list;
                        switch (group.name)
                        {
                            case "LayerGrou":
                                list = _layerList;
                                if (_map == null || list.selectedIndex == -1) {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                //添加一层，数据加入一层地图
                                MapManager.Instance.RemoveMap(list.selectedIndex);
                                list.numItems--;
                                break;
                            case "InsertRoomGrou":
                                list = _lists[GMConfig.ProductType.InsertRoom];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.InsertRoom, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "EventGrou":
                                list = _lists[GMConfig.ProductType.Event];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.Event, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "ItemGrou":
                                list = _lists[GMConfig.ProductType.Item];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.Item, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "CardGrou":
                                list = _lists[GMConfig.ProductType.Card];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.Card, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "BossGrou":
                                list = _lists[GMConfig.ProductType.Boss];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.Boss, list.selectedIndex);
                                list.numItems--;
                                break;  
                            case "BossRetinueGrou":
                                list = _lists[GMConfig.ProductType.BossRetinue];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.BossRetinue, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "EliteGrou":
                                list = _lists[GMConfig.ProductType.Elite];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.Elite, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "EliteRetinueGrou":
                                list = _lists[GMConfig.ProductType.EliteRetinue];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.EliteRetinue, list.selectedIndex);
                                list.numItems--;
                                break;
                            case "MonsterGrou":
                                list = _lists[GMConfig.ProductType.Monster];
                                if (_map == null || list.selectedIndex == -1)
                                {
                                    FUIMain.TipPanel("请先选择列表项！");
                                    return;
                                }
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.Monster, list.selectedIndex);
                                list.numItems--;
                                break;

                        }
                    }
                });
            });
        }

        foreach (GComponent com in roomGComps)
        {
            com.GetChild("AddBtn").asButton.onClick.Add(() =>
            {
                switch (com.name)
                {
                    case "BossRoom":
                        LoadCommonListPanel(GMConfig.ProductType.BossRoom);
                        break;
                    case "EliteRoom":
                        LoadCommonListPanel(GMConfig.ProductType.EliteRoom);
                        break;
                    case "MonsterRoom":
                        LoadCommonListPanel(GMConfig.ProductType.MonsterRoom);
                        break;
                }
            });

            com.GetChild("RemoveBtn").asButton.onClick.Add(() =>
            {
                GList list;
                switch (com.name)
                {
                    case "BossRoom":
                        list = _lists[GMConfig.ProductType.BossRoom];
                        if (!SelectedItem(list)) return;
                        FUIMain.TipPanel("是否确定删除本条数据？", (status) =>
                        {
                            if ((int)status == 1)
                            {
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.BossRoom, list.selectedIndex);
                                list.numItems--;
                            }
                        });
                        break;
                    case "EliteRoom":
                        list = _lists[GMConfig.ProductType.EliteRoom];
                        if (!SelectedItem(list)) return;
                        FUIMain.TipPanel("是否确定删除本条数据？", (status) =>
                        {
                            if ((int)status == 1)
                            {
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.EliteRoom, list.selectedIndex);
                                list.numItems--;
                            }
                        });
                        break;
                    case "MonsterRoom":
                        list = _lists[GMConfig.ProductType.MonsterRoom];
                        if (!SelectedItem(list)) return;
                        FUIMain.TipPanel("是否确定删除本条数据？", (status) =>
                        {
                            if ((int)status == 1)
                            {
                                MapManager.Instance.RemoveKeyValue(_map, GMConfig.ProductType.MonsterRoom, list.selectedIndex);
                                list.numItems--;
                            }
                        });
                        break;
                }
            });
        }

        this.contentPane.GetChild("SaveBtn").onClick.Add(SaveMapConfig);

        this.contentPane.GetChild("ExitBtn").onClick.Add(() =>
        {
            this.Hide();
        });
    }
    bool SelectedItem(GList list){
        if (_map == null || list.selectedIndex == -1)
        {
            FUIMain.TipPanel("请先选择列表项！");
            return false;
        }
        return true;
    }

    void LoadCommonListPanel(GMConfig.ProductType productType) {
        FCommonListMediator commonListPanel = FUIMain.ShowPanel(GMConfig.PanelType.CommonListPanel) as FCommonListMediator;
        commonListPanel.SetLoadWithProduct(productType,_lists,_map,fixedRoomList,blocks);
        commonListPanel.SetRenderer(productType,fixedRoomList,blocks);
    }

    //初始化所有列表
    void InitLists(){

        //初始化层列表
        _layerList.itemRenderer = (int index, GObject obj) =>
        {
            GButton button = obj.asButton;
            button.title = string.Format("第{0}层", index + 1);
        };

        _layerList.numItems = MapManager.Instance.MapCount;
        _layerList.selectedIndex = MapManager.Instance.layerIndex;
        _map = MapManager.Instance.GetMap(_layerList.selectedIndex);
        
        //每次切换索引，保存
        MapManager.Instance.OnSelectLayer = OnSelectLayer;
        //当层列表点击时，其他所有配置更新 TODO：
        _layerList.onClickItem.Add(() => {
            if (MapManager.Instance.OnSelectLayer != null) MapManager.Instance.OnSelectLayer();
            InitRoom();
        });
        //列表更新
        for (int i = 1; i < Enum.GetNames(typeof(GMConfig.ProductType)).Length; i++)
        {
            GMConfig.ProductType type = (GMConfig.ProductType)i;
            _lists[type].itemRenderer = (int index, GObject obj) =>
            {
                GButton btn = obj.asButton;
                KeyValue item = MapManager.Instance.GetKeyValue(_map, type, index);
                btn.title = item.name;
                GTextInput numInput = btn.GetChild("num").asTextInput;
                if((int)type < (int)GMConfig.ProductType.BossRoom) 
                    numInput.text = item.value.ToString();
                else
                    numInput.text = string.Format("{0}-{1}",item.value.ToString(), item.max.ToString());

                numInput.onChanged.Add(() =>
                {
                    int target = _lists[type].GetChildIndex(btn);
                    if ((int)type < (int)GMConfig.ProductType.BossRoom) {
                        int value = 0;
                        int.TryParse(numInput.text, out value);
                        MapManager.Instance.ReplaceKeyValue(_map, type, target, new KeyValue(item.name, value));
                    }else {
                        string str = numInput.text;
                        string[] result = str.Split('-');
                        int value = 0;
                        int max = 1;
                        int.TryParse(result[0], out value);
                        int.TryParse(result[1], out max);
                        MapManager.Instance.ReplaceKeyValue(_map, type, target, new KeyValue(item.name, value,max));

                    }
                });
                
                
            };
        }
       
        InitRoom();
    }
    //初始化房间配置(切换map)
    void InitRoom(){
        fixedRoomList = Utils.LoadByJson<List<FixedRoom>>(Application.dataPath, "fixedRoomList.json");

        for (int i = 1; i < Enum.GetNames(typeof(GMConfig.ProductType)).Length; i++)
        {
            GMConfig.ProductType type = (GMConfig.ProductType)i;
            _lists[type].numItems = MapManager.Instance.GetKeyValueCount(_map, type);
        }

        //初始化地图物品数量
        for (int i = 0; i < _countRangeDic.Count; i++)
        {
            GMConfig.CountRange countRange = (GMConfig.CountRange)Enum.Parse(typeof(GMConfig.CountRange), i.ToString());
            if (_countRangeDic[countRange].Count > 1 && _countRangeDic[countRange][0] != null)
            {
                ProductCount productCount = MapManager.Instance.GetCountRange(_map, countRange);
                _countRangeDic[countRange][0].text = productCount.min.ToString();
                _countRangeDic[countRange][1].text = productCount.max.ToString();
            }
        }

        if (_map == null || _map.LayerIndex == -1) {
            for (int i = 0; i < roomGComps.Count; i++)
            {
                roomGComps[i].GetChild("RoomTrigger").asButton.GetController("button").selectedIndex = 0;
                roomGComps[i].GetChild("roomMinInput_01").asTextInput.text = "";
                roomGComps[i].GetChild("roomMinInput_02").asTextInput.text = "";
                roomGComps[i].GetChild("roomMaxInput_01").asTextInput.text = "";
                roomGComps[i].GetChild("roomMaxInput_02").asTextInput.text = "";
            }
            return;
        }

        string[] items = new string[fixedRoomList.Count];
        for (int i = 0; i < fixedRoomList.Count; i++)
        {
            items[i] = fixedRoomList[i].name;
        }
        //初始化模板生成配置
        if (fixedRoomList != null)
        {
            for (int i = 0; i < roomGComps.Count; i++)
            {
                GComboBox combox = roomGComps[i].GetChild("ModeDropBox").asComboBox;
                combox.items = items;
                //编辑模板按钮
                roomGComps[i].GetChild("EditBtn").asButton.onClick.Add(() =>
                {
                    FUIMain._funcCtrl.selectedIndex = 4;
                    FRoomPanelMediator roomPanel = FUIMain.GetWindow(GMConfig.PanelType.RoomPanel) as FRoomPanelMediator;
                    roomPanel.LoadFixedRoom(combox.selectedIndex);
                });
            }
        }

        foreach (Room room in _map.roomList)
        {
            int level = (int)room.roomLevel;
            GButton roomTrigger = roomGComps[level].GetChild("RoomTrigger").asButton;
            roomTrigger.GetController("button").selectedIndex = 1;
            roomGComps[level].GetController("ModeController").selectedIndex = (int)room.roomType;
            GComboBox combox = roomGComps[level].GetChild("ModeDropBox").asComboBox;

            if (string.IsNullOrEmpty(room.name)){
                combox.title = "";
                roomGComps[level].GetChild("roomMinInput_01").asTextInput.text = room.minRect.width.ToString();
                roomGComps[level].GetChild("roomMinInput_02").asTextInput.text = room.minRect.height.ToString();
                roomGComps[level].GetChild("roomMaxInput_01").asTextInput.text = room.maxRect.width.ToString();
                roomGComps[level].GetChild("roomMaxInput_02").asTextInput.text = room.maxRect.height.ToString();
            }else{
                bool existModel = false;
                for (int i = 0; i < fixedRoomList.Count; i++)
                {
                    if (fixedRoomList[i].name == room.name){
                        existModel = true;
                        break;
                    }
                }
                //初始化下拉框
                if (existModel)
                    combox.title = room.name;
                else
                    combox.title = "";
            }
        }
    }
    void OnSelectLayer(){
        MapManager.Instance.layerIndex = _layerList.selectedIndex;
        _map = MapManager.Instance.GetMap(_layerList.selectedIndex);
    }

    void SaveMapConfig(){
        //把房间信息取出
        for (int i = 0; i < roomGComps.Count; i++)
        {
            GButton roomTrigger = roomGComps[i].GetChild("RoomTrigger").asButton;
            //房间勾选
            if (roomTrigger.GetController("button").selectedIndex == 1) {
                //房间生成模式
                int roomType = roomGComps[i].GetController("ModeController").selectedIndex;
                if (roomType == 0){
                    int minWidth = 0;
                    int minHeight = 0;
                    int maxWidth = 0;
                    int maxHeight = 0;
                    int.TryParse(roomGComps[i].GetChild("roomMinInput_01").asTextInput.text,out minWidth);
                    int.TryParse(roomGComps[i].GetChild("roomMinInput_02").asTextInput.text, out minHeight);
                    int.TryParse(roomGComps[i].GetChild("roomMaxInput_01").asTextInput.text, out maxWidth);
                    int.TryParse(roomGComps[i].GetChild("roomMaxInput_02").asTextInput.text,out maxHeight);
                    
                    _map.AddRoom(i,new Room(i,roomType,minWidth,minHeight,maxWidth,maxHeight));
                }else {
                    GComboBox combox = roomGComps[i].GetChild("ModeDropBox").asComboBox;
                    _map.AddRoom(i, new Room(i, roomType, combox.title));
                }
            }
        }
        //存储地图物品数量
        for (int i = 0; i < _countRangeDic.Count; i++)
        {
            GMConfig.CountRange countRange = (GMConfig.CountRange)Enum.Parse(typeof(GMConfig.CountRange), i.ToString());
            int min = 0;
            int max = 0;
            int.TryParse(_countRangeDic[countRange][0].text,out min);
            int.TryParse(_countRangeDic[countRange][1].text,out max);
            MapManager.Instance.ReplaceCountRange(_map,countRange,new ProductCount(min,max));
        }
        Map mapClone = _map.DeepClone();
        mapClone.LayerIndex = _layerList.selectedIndex;
        MapManager.Instance.ReplaceMap(mapClone, _layerList.selectedIndex);

        bool result = MapManager.Instance.SaveMap();
        FUIMain.TipPanel(result ? "保存成功！" : "保存失败");
        
    }
}
